package com.wandian.texas;

import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

import com.wandian.texas.dao.Impl.GameRoomDaoImpl;
import com.wandian.texas.db.CommonDaoManager;
import com.wandian.texas.db.DBMgr;
import com.wandian.texas.db.DaoManager;
import com.wandian.texas.demo.Test;
import com.wandian.texas.entity.CornucopiaEntity;
import com.wandian.texas.entity.GameRoomEntity;
import com.wandian.texas.entity.LastAction;
import com.wandian.texas.entity.SNAPCARDS;
import com.wandian.texas.entity.UserGameEntity;
import com.wandian.texas.entity.UserInfoEntity;
import com.wandian.texas.protocol.Protocol;
import com.wandian.util.Log;
import com.wandian.xml.RoomConfigItem;

/**
 * 游戏池，对正在进行游戏的进行管理
 * 
 * @author long
 * @Create 2012-10-27 下午3:58:40
 * @QQ 108232706
 * @version 1.0
 * @description GamePool
 */
public class TestGamePool {

	//	private static final Map<Integer, GameRoomEntity> gameMap = new ConcurrentHashMap<Integer, GameRoomEntity>();// 根据roomid找
	public final static String[] arrCardType = new String[] { "高牌", "一对", "两对", "三条", "顺子", "同花", "葫芦", "四条", "同花顺", "皇家同花顺" };
	public final static String[] ArrLastAction = new String[] { "看牌", "弃牌", "跟注", "加注", "全押" };
	public final static String[] arrHuase = new String[] { "", "d", "c", "h", "s" };
	public final static String[] arrHuaseName = new String[] { "方块", "梅花", "红桃", "黑桃" };

	// private static final ArrayList<Game> gameList = new ArrayList<Game>();

	//	public static GameRoomEntity getGame(int gameId) {
	//		return gameMap.get(gameId);
	//	}

	public static String getLastAction(int lastAction) {
		if (lastAction > 1 && lastAction < 5) {
			return ArrLastAction[lastAction - 1];
		}
		return "";
	}

	public static void sendStandup(SessionObject session, BaseCommandObject cmdObject, boolean kick) {
		UserInfoEntity user = session.getUser();
		cmdObject.sessionObject = session;
		if (user != null && user.roomId > 0) {
			cmdObject.setCmd(Protocol.StandUpCmd);
			// 当前房间玩家都通知
			cmdObject.writeBegin();
			cmdObject.writeInt(user.seatId);
			// 身上钱发生变化，存入兑换表
			// user.money += user.stake;
			// user.stake = 0;
			cmdObject.writeFloat(user.money);
			cmdObject.writeInt(1);
			cmdObject.writeEnd();
//			UserMgr.I().broadCastToRoomUsers(cmdObject);
			RoomMgr.sendStandup(session, cmdObject.dbIndex, cmdObject, kick);
		} else {
			Log.error("不合法用户操作");
		}
	}

	public static GameRoomDaoImpl gameRoomDao(int dbIndex) {
		if (dbIndex > -1) {
			return DaoManager.GameRoomDao(dbIndex);// 换成存储过程去新增
		} else {
			return CommonDaoManager.GameRoomDao(0);
		}
	}

	public static boolean startGame(int roomid, int dbIndex) {
		RoomConfigItem room = RoomMgr.roomsMap.get(roomid);
		if (room == null || room.isPlaying()) {
			//			Log.debug(String.format("[GamePool]游戏开始失败,房间游戏正在开始,当前游戏状态:%s", room.toString()));
			return false;
		}
		room.GameSeatLock().lock();
		try {
			room.beforStartGame();
			// 大于2人，可以开始游戏,坐下的人最小筹码合法
			if (room.roomGameSeatSize() >= 2) {
				room.isPlaying(true);
				try {
					// 游戏开始，预设发牌
					if (!PreparedStartGame(room, dbIndex)) {
						//					Log.debug(String.format("[GamePool]游戏开始失败,随机发牌失败,当前游戏状态:%s", room.toString()));
						room.isPlaying(false);
						return false;
					} else {
						room.isPlaying(true);
						room.setMaxStake();
						room.doingGameOver(false, 0);
						return true;
					}
				} catch (Exception e) {
					e.printStackTrace();
					//				Log.error(String.format("[GamePool]游戏开始失败,%s", e));
					room.isPlaying(false);
					return false;
				}
			}
		} finally {
			room.GameSeatLock().unlock();
		}
		//		Log.debug(String.format("[GamePool]游戏开始失败,当前游戏状态:%s", room.toString()));
		return false;
	}

	public final static String[] pokervalues = new String[] { "A", "2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K" };
	public static int setDealerId = 2;
	public static int GameId = 9;
	public static boolean isHistory = true;
	public static int[] seatIdx;// = new int[] { 0,73,0,0,0,75,0,76,0};
	public static int[] publicAndSeatPokerIndex;// = new int[] { 20, 11, 47, 51, 17, 28, 45, 39, 34, 4, 1, 43, 7, 36, 44, 8, 32, 27, 12, 33, 35, 16, 24 };

	/**
	 * @param room
	 * @param dbIndex
	 * @return
	 * @throws Exception
	 */
	/**
	 * @param room
	 * @param dbIndex
	 * @return
	 * @throws Exception
	 */
	/**
	 * @param room
	 * @param dbIndex
	 * @return
	 * @throws Exception
	 */
	private static boolean PreparedStartGame(RoomConfigItem room, int dbIndex) throws Exception {
		// Step 1,合法性检查
		GameRoomEntity gameRoom = room.gameRoom();
		UserInfoEntity user = null;
		if (room.roomSeatSize() < 2) {
			//Log.debug(String.format("[GamePool]游戏开始失败，坐位人数不够2人"));
			return false;
		}
		//在游戏结束的时候清空状态信息，开始可以不做重复工作?
		//		room.reset();
		// gameRoom.reset();
		gameRoom.currPublicCardLen = 0;
		// Step2 将坐位id数组排序,产生大小盲,随机洗牌
		// 洗牌

		// 定庄家以及大小盲
		// 如果是新的一局开始
		//Collections.sort(gameRoom.userSeats);
		CalculateCard.sortAsc(gameRoom.userSeats, gameRoom.userSeatsLen);
		//
		// int findCount = 0;
		if (isHistory) {
			gameRoom.isNewGame = false;
			gameRoom.setDealerId(setDealerId);
			gameRoom.prevId = 1;
		} else {
			findDealerId(gameRoom);
		}
		//		Log.debug(String.format("[GamePool]游戏开始，产生庄家:%s", gameRoom.getDealerId()));
		GameRoomDaoImpl gameDao = GamePool.gameRoomDao(dbIndex);
		gameRoom.gameOverLen = 0;
		UserGameEntity userGame;
		for (int i = 0; i < gameRoom.userSeatsLen; i++) {
			userGame = gameRoom.gameOverUsers[gameRoom.userSeats[i] - 1];
			userGame.user = gameRoom.seatUsers[userGame.seatId - 1].getUser();
			userGame.lastAction = 0;
//			userGame.seatId = i;
			userGame.user.state = GameData.PLAYING_GAME;
			gameRoom.gameOverSeats[i] = gameRoom.userSeats[i];
			gameRoom.gameOverLen++;
		}
		// 设置大小盲，游戏基础数据
		// 发手牌
		setStartGameRoomInfo(gameRoom, room, gameDao);
		// Step3 先发公共牌
		int seatId;// 临时变量
		String[] pokers = gameRoom.pokers;
		if (isHistory) {
			gameRoom.publicAndSeatPokerIndex = TestGamePool.publicAndSeatPokerIndex;
		} else {
			setBonusCard(room);
		}
		// SessionObject session;
		// Step 4给坐位玩家发牌，并下注,
		// 判断牌型，恰好三种，如果【规则】允许出，继续发牌发出去，如果不允许洗牌
		// 【1个小时，中心服务器】
//		for (int i = 0; i < 5; i++) {
//			gameRoom.PublicCard[i] = pokers[i];
//			gameRoom.PublicAllCard.concat(gameRoom.PublicCard[i]);
//		}
		gameRoom.setPublicCard();
		//《辅助功能
		Log.info("=======publicAndSeatPokerIndex=========");
		String temp = "";
		for (int i = 0; i < publicAndSeatPokerIndex.length; i++) {
			temp += publicAndSeatPokerIndex[i] + ",";
		}
		Log.info(temp);
		Log.info("=======发牌结果=========");
		temp = "公共牌:";
		for (int i = 0; i < 5; i++) {
			temp += pokers[publicAndSeatPokerIndex[i]] + ",";
		}
		temp += "9个坐位的牌:";
		//5(5+9)~
		for (int i = 0; i < gameRoom.userSeatsLen; i++) {
			seatId = gameRoom.userSeats[i];
			temp += "坐位:[" + seatId + "]" + gameRoom.getSeatPoker(seatId, 1) + ",";
			temp += gameRoom.getSeatPoker(seatId, 2) + ",";
			if (gameRoom.gameOverUsers[seatId - 1].user != null) {
				temp += "有人userid:" + gameRoom.gameOverUsers[seatId - 1].user.userId + " username:" + gameRoom.gameOverUsers[seatId - 1].user.userName;
			} else {
				temp += "无人";
			}
		}
		Log.info(temp);

		//辅助功能》
		for (int i = 0; i < gameRoom.userSeatsLen; i++) {
			seatId = gameRoom.userSeats[i];
			if (gameRoom.seatUsers[seatId - 1] != null) {
				user = gameRoom.seatUsers[seatId - 1].getUser();
				userGame = gameRoom.gameOverUsers[seatId - 1];
				if (!gameRoom.gameUsers.contains(user)) {
					gameRoom.gameUsers.add(user);
					gameRoom.gameSessions.add(gameRoom.seatUsers[seatId - 1]);
				}
				if (gameRoom.callChip(seatId) <= 0 && user.isNew && gameRoom.prevId > 1 && !gameRoom.isNewGame) {
					gameRoom.callChip(seatId, room.newChip);
					gameRoom.NewUserIds += user.userId + "|";
					// 下注赢钱记录
					gameDao.executeUpdate("sp_AddPlayMoneyLog", DBMgr.TexasPokerDB, user.userId, user.AccountId, room.newChip, 0);
					gameDao.addGameLog(gameRoom,room.gameId(), room.step(), user, room.SNAPCARDS().value(), 0, room.newChip, room.curSeatChip(user.seatId), room.curSeatTotalChip(user.seatId), "新人下注+" + room.newChip);
					//					Log.debug(String.format("[GamePool]新玩家%s首次下注:%s", user.nickName, gameRoom.callChip(seatId)));
				}
				user.isNew = false;// 开始了一把,老玩家了
				//				user.clearStep();
				user.card1 = gameRoom.getSeatPoker(seatId, 1);
				user.card2 = gameRoom.getSeatPoker(seatId, 2);
				userGame.cards[0] = user.card1;
				userGame.cards[1] = user.card2;
				//				Log.debug(String.format("[GamePool]给坐位发牌，seat:%s,card1:%s,card2:%s", seatId, user.card1, user.card2));
			} else {
				//				Log.error(String.format("[GamePool]给坐位发牌,坐位上玩家居然null"));
			}
		}
		// Step 5 ，初始化游戏参数，step,Stake,第几回
		gameRoom.step = 0;
		gameRoom.snapCards = SNAPCARDS.SNAPCARDS_START;
		// room.maxRaiseSeatId(gameRoom.MinBindSeatId);
		room.curSeatId(room.MaxBindSeatId());// 设置起始出牌的左手，这样在operate里可以调用封装的nextuser操作
		// Step 6 游戏开始,存入数据库
		gameRoom.beforeAdd();
		// gameDao.addGameRoom(gameRoom);// 换成存储过程去新增
		if (gameDao.addBeginGameLog(gameRoom)) {
			//			Log.debug(String.format("[GamePool]新游戏开始,保存开始成功,游戏状态:%s", gameRoom.toString()));
			saveBlindMoney(gameRoom, room, gameDao);
			// 游戏开始成功,插入哈希表
			for (int i = 0; i < gameRoom.userSeatsLen; i++) {
				seatId = gameRoom.userSeats[i];
				if (gameRoom.seatUsers[seatId - 1] != null) {
					userGame = gameRoom.gameOverUsers[seatId - 1];
					//已经开始的游戏，后来进来的人自动下注
					if (gameRoom.callChip(seatId) <= 0 && user.isNew && gameRoom.prevId > 0 && !gameRoom.isNewGame) {
						gameRoom.callChip(seatId, room.newChip);
						gameRoom.NewUserIds += user.userId + "|";
						if (userGame.user.stake <= 0) {
							gameRoom.allinCount++;
						}
						// 下注赢钱记录
						gameDao.executeUpdate("sp_AddPlayMoneyLog", DBMgr.TexasPokerDB, userGame.user.userId, user.AccountId, room.newChip, 0);
						gameDao.addGameLog(gameRoom,room.gameId(), room.step(), userGame.user, room.SNAPCARDS().value(), 0, room.newChip, room.curSeatChip(user.seatId), room.curSeatTotalChip(user.seatId), "新人下注+" + room.newChip);
						//					Log.debug(String.format("[GamePool]新玩家%s首次下注:%s", user.nickName, gameRoom.callChip(seatId)));
					}
					user.isNew = false;// 开始了一把,老玩家了
				}
			}
			return true;
		} else {
			//			Log.debug(String.format("[GamePool]新游戏开始,失败,保存开始失败,游戏状态:%s", gameRoom.toString()));
		}
		return false;
	}

	private static void findDealerId(GameRoomEntity gameRoom) {
		gameRoom.prevId = gameRoom.GameId;
		if (gameRoom.prevId < 1 || gameRoom.isNewGame) {
			gameRoom.setDealerId(gameRoom.getNextSeat(0));
		} else {
			int tempDealer = gameRoom.getDealerId();
			gameRoom.setDealerId(gameRoom.getNextSeat(tempDealer));
		}
	}

	private static void setBonusCard(RoomConfigItem room) throws Exception {
		GameRoomEntity gameRoom = room.gameRoom();
		int[] publicAndSeatPokerIndex = gameRoom.publicAndSeatPokerIndex;
		int seatId;
		UserGameEntity userGame;
		UserInfoEntity user;
		// 允许出积宝，并且积宝没有被使用[同一个时间段只能出一个积宝,游戏端产生,发送1,要确认了isGenerateCornucopia=false]
		if (room.isAllowCornucopia() && !room.isUsingCornucopia()) {
			gameRoom.useLastPoker();
			room.isUsingCornucopia(true);
			Log.info("使用积宝牌发牌");
			gameRoom.setPublicCard();
			// 判断user在不在，按坐位发，按坐位推移
			// 如若出现好几个积宝，则将当前牌从5 + 9 - 1 + 9+1处换牌，直到不是积宝为止
			int toCornucopiaSeatId = room.cornucopiaSeatId();
			if (gameRoom.userSeats[room.cornucopiaSeatId()] < 1) {
				toCornucopiaSeatId = room.getNextSeat(room.cornucopiaSeatId());
				// 从第3个移动到第4坐位，第3坐位空,即使重复牌，也不影响在坐的重复
				int tempCard = publicAndSeatPokerIndex[5 + toCornucopiaSeatId - 1];
				publicAndSeatPokerIndex[5 + toCornucopiaSeatId - 1] = publicAndSeatPokerIndex[5 + room.cornucopiaSeatId() - 1];
				publicAndSeatPokerIndex[5 + room.cornucopiaSeatId() - 1] = tempCard;
				tempCard = publicAndSeatPokerIndex[5 + toCornucopiaSeatId - 1 + 9];
				publicAndSeatPokerIndex[5 + toCornucopiaSeatId - 1 + 9] = publicAndSeatPokerIndex[5 + room.cornucopiaSeatId() - 1 + 9];
				publicAndSeatPokerIndex[5 + room.cornucopiaSeatId() - 1 + 9] = tempCard;
				room.cornucopiaSeatId(toCornucopiaSeatId);
			}
			//每次模拟之前，清除先前计算的结果
			for (int i = 0; i < gameRoom.gameOverUsers.length; i++) {
				gameRoom.gameOverUsers[i].clearCard();
			}
			// 测试本次是不是出现一个积宝牌，多了替掉
			for (int i = 0; i < gameRoom.gameOverUsers.length; i++) {
				userGame = gameRoom.gameOverUsers[i];
				if (userGame.user == null)
					continue;
				seatId = userGame.seatId;
				userGame.cards[0] = gameRoom.getSeatPoker(userGame.seatId, 1);
				userGame.cards[1] = gameRoom.getSeatPoker(userGame.seatId, 2);
				userGame.calculateCard();
				//				WinCardEntity winCardEntity = GamePool.countCardType(room.testPublicCards, new String[] { card1, card2 });
				//				Log.debug(String.format("[GamePool]使用积宝出现时候,模拟给坐位发牌，seat:%s,牌型：%s,card1:%s,card2:%s", seatId, winCardEntity.getType(), card1, card2));
				// 模拟，出现了积宝牌
				if (userGame.getType() == 9 || userGame.getType() == 8 || userGame.getType() == 7) {
					//如果需要发积宝的位置出现积宝，并且类型是中心端控制的,正常，否则就是前面移位不对
					if (seatId == toCornucopiaSeatId) {
						user = gameRoom.seatUsers[seatId - 1].getUser();
						room.cornucopiaUserId(user.userId);
						room.cornucopiaidx(user.AccountId);
						//						Log.info("使用积宝出现时候,模拟给坐位发牌,坐位" + toCornucopiaSeatId + " user " + user.nickName + "将产生积宝");
						if (userGame.getType() != room.cornucopiaCardType()) {
							throw new Exception("使用积宝发牌,牌型与上次存的牌型不一致");
						}
					} else {
						//一个桌只能出一个积宝，其他位置的要替换掉，为了简单只替换card1
						// 52--9*2+5=23,索引23开始替换牌
						boolean replaceCard = false;
						/*String oldcard1 = userGame.cards[0];
						for (int j = 23; j < 52; j++) {
							userGame.cards[0] = pokers[j];
							userGame.calculateCard();
							if (userGame.getType() == 9 || userGame.getType() == 8 || userGame.getType() == 7) {
								continue;
							} else {
								pokers[j] = oldcard1;
								pokers[5 + seatId - 1] = userGame.cards[0];
								replaceCard = true;
								break;
							}
						}*/
						//循环替换当前玩家的积宝牌
						while (true) {
							gameRoom.replacePoker(seatId, 1);
							userGame.cards[0] = gameRoom.getSeatPoker(seatId, 1);
							userGame.calculateCard();
							if (userGame.getType() == 9 || userGame.getType() == 8 || userGame.getType() == 7) {
								continue;
							} else {
								break;
							}
						}
						// 如果没有替换掉不该出的积宝牌，报异常错误
						if (!replaceCard) {
							throw new Exception("没有替换掉不该出的积宝牌");
						}
					}
				}
			}
			// 通知服务端，使用了指标发牌
			GameServer.requestor.requestUsingdCornucopia(true, room.cornucopiaCallBack(), room.cornucopiaCardType(), room.id, room.cornucopiaSeatId(), room.cornucopiaUserId(), room.cornucopiaidx());
		} else {
			boolean isCornucopia = true;
			/*
			// 模拟数据测试,如果想快速测试游戏服与中心积宝交互，开启
			// 2位置4带1
			String[] testData = new String[] { "As", "Ad", "Jc", "Tc", "Ks", "Qc", "Ac", "Qd", "3d", "2c", "Kd", "7c", "4c", "2h", "4s", "Ah", "Qh", "5h", "2d", "9s", "Kc", "5c", "9h", "5d", "8s", "8d", "4h", "Jd", "6s", "Qs", "Th", "2s", "Ts", "7d", "8c", "7h", "6c", "3s", "3c", "3h", "7s", "Kh", "Jh", "4d", "6h", "Td", "Js", "6d", "9c", "8h", "9d", "5s" };
			// 2位置同花顺
			String[] testData2 = new String[] { "As", "2s", "3s", "4s", "Ad", "Jc", "5s", "Tc", "Ks", "Qc", "Ac", "Qd", "3d", "2c", "Kd", "7c", "4c", "2h", "Ah", "Qh", "5h", "2d", "9s", "Kc", "5c", "9h", "5d", "8s", "8d", "4h", "Jd", "6s", "Qs", "Th", "Ts", "7d", "8c", "7h", "6c", "3c", "3h", "7s", "Kh", "Jh", "4d", "6h", "Td", "Js", "6d", "9c", "8h", "9d" };
			// 2位置皇家同花顺
			String[] testData3 = new String[] { "As", "Ks", "Qs", "Js", "2s", "3s", "Ts", "4s", "Ad", "Jc", "5s", "Tc", "Qc", "Ac", "Qd", "3d", "2c", "Kd", "7c", "4c", "2h", "Ah", "Qh", "5h", "2d", "9s", "Kc", "5c", "9h", "5d", "8s", "8d", "4h", "Jd", "6s", "Th", "7d", "8c", "7h", "6c", "3c", "3h", "7s", "Kh", "Jh", "4d", "6h", "Td", "6d", "9c", "8h", "9d" };
			pokers = new java.util.ArrayList<String>();
			for (int i = 0; i < testData.length; i++) {
				pokers.add(testData[i]);
			}*/
//					pokers = new java.util.ArrayList<String>(13 * 4);
//					for (int i = 0; i < pokervalues.length; i++) {
//						pokers.add(pokervalues[i] + PokerColor.CLUB.value());
//						pokers.add(pokervalues[i] + PokerColor.DIAMOND.value());
//						pokers.add(pokervalues[i] + PokerColor.HEART.value());
//						pokers.add(pokervalues[i] + PokerColor.SPADE.value());
//					}
//					Collections.shuffle(pokers);
			gameRoom.shuffle();
			//			Log.debug(String.format("[GamePool]游戏随机生成了一组牌"));
			while (isCornucopia) {
//						for (int i = 0; i < 5; i++) {
//							room.PublicCards()[i] = pokers[i];
//						}
				gameRoom.setPublicCard();
				int cornucopiaCount = 0;
				boolean isMutilCornucopia = false;
				for (int i = 0; i < gameRoom.userSeatsLen; i++) {
					seatId = gameRoom.userSeats[i];
					if (gameRoom.seatUsers[seatId - 1] != null) {
						userGame = gameRoom.gameOverUsers[seatId - 1];
						userGame.cards[0] = gameRoom.getSeatPoker(seatId, 1);
						userGame.cards[1] = gameRoom.getSeatPoker(seatId, 2);
						userGame.calculateCard();
//								WinCardEntity winCardEntity = GamePool.countCardType(room.testPublicCards, new String[] { pokers.get(5 + seatId - 1), pokers.get(5 + seatId - 1 + 9) });
						//						Log.debug(String.format("[GamePool]模拟给坐位发牌，seat:%s,card1:%s,card2:%s", seatId, card1, card2));
						// 模拟，出现了积宝牌
						if (userGame.getType() == 9 || userGame.getType() == 8 || userGame.getType() == 7) {
							if (cornucopiaCount > 0) {
								isMutilCornucopia = true;
								break;
							}
							user = gameRoom.seatUsers[seatId - 1].getUser();
							cornucopiaCount++;
							room.cornucopiaCardType(userGame.getType());
							room.cornucopiaUserId( user.userId);
							room.cornucopiaSeatId(seatId);
						}

					}
				}
				// 如果产生一个积宝，算有效
				if (cornucopiaCount == 0) {
					isCornucopia = false;
					// room.isGenerateCornucopia = false;
					break;
				}
				if (cornucopiaCount == 1 && !isMutilCornucopia) {
					// 如果上一把产生过积宝牌，本局不能出，要一直等中心端确认
					if (!room.isGenerateCornucopia()) {
						gameRoom.saveLastPoker();
						room.isGenerateCornucopia(true);
						// 告诉中心服务器，洗到积宝牌，并且继续洗一个无积宝的牌
						GameServer.requestor.requestAllowCornucopia(room.cornucopiaCardType(), room.id, room.cornucopiaSeatId(), room.cornucopiaUserId(), room.cornucopiaidx());
					}
//							Collections.shuffle(pokers);// 抛弃，继续洗牌
					gameRoom.shuffle();
				} else {
					cornucopiaCount = 0;
					// room.isGenerateCornucopia = false;
					Log.error("房间产生了好几个积宝，视为无效,继续洗牌找");
//							Collections.shuffle(pokers);
					gameRoom.shuffle();
				}
			}
		}
		// SessionObject session;
		// Step 4给坐位玩家发牌，并下注,
		// 判断牌型，恰好三种，如果【规则】允许出，继续发牌发出去，如果不允许洗牌
		// 【1个小时，中心服务器】
//				for (int i = 0; i < 5; i++) {
//					gameRoom.PublicCard[i] = pokers[i];
//					gameRoom.PublicAllCard.concat(gameRoom.PublicCard[i]);
//				}
	}

	private static void setStartGameRoomInfo(GameRoomEntity gameRoom, RoomConfigItem room, GameRoomDaoImpl gameDao) {
		gameRoom.MinBindSeatId = gameRoom.getNextSeat(gameRoom.getDealerId());
		gameRoom.MaxBindSeatId = gameRoom.getNextSeat(gameRoom.MinBindSeatId);
		// Log.debug("小盲注开始筹码:" + userMin);
		// Log.debug("大盲注开始筹码:" + userMax);
		gameRoom.MinBindUserId = gameRoom.getUser(gameRoom.MinBindSeatId).userId;
		gameRoom.MaxBindUserId = gameRoom.getUser(gameRoom.MaxBindSeatId).userId;
		//		Log.debug(String.format("找到大盲:坐位%s 用户id%s 下注1%s 筹码 %s,小盲:坐位%s 用户id%s 下注%s  筹码 %s", userMax.seatId, userMax.userId, gameRoom.callChip(userMax.seatId), userMax.stake, userMin.seatId, userMin.userId, gameRoom.callChip(userMin.seatId), userMin.stake));
		gameRoom.MinBind = room.minBlind;
		gameRoom.MaxBind = room.maxBlind;
		gameRoom.MinStake = room.minTake;
		gameRoom.MaxStake = room.maxTake;
		gameRoom.NewChip = room.newChip;
		gameRoom.maxRaiseSeatId = gameRoom.MaxBindSeatId;
	}

	private static void saveBlindMoney(GameRoomEntity gameRoom, RoomConfigItem room, GameRoomDaoImpl gameDao) {
		UserInfoEntity userMin = gameRoom.getUser(gameRoom.MinBindSeatId);
		UserInfoEntity userMax = gameRoom.getUser(gameRoom.MaxBindSeatId);
		gameRoom.callChip(gameRoom.MinBindSeatId, room.minBlind);
		gameDao.addGameLog(gameRoom,room.gameId(), room.step(), userMin, room.SNAPCARDS().value(), 0, room.minBlind, room.curSeatChip(userMin.seatId), room.curSeatTotalChip(userMin.seatId), "小盲+" + room.minBlind);
		// 下注赢钱记录
		gameDao.executeUpdate("sp_AddPlayMoneyLog", DBMgr.TexasPokerDB, gameRoom.MinBindUserId, gameRoom.getUser(gameRoom.MinBindSeatId).AccountId, room.minBlind, 0);

		gameRoom.callChip(gameRoom.MaxBindSeatId, room.maxBlind);
		// 下注赢钱记录
		gameDao.executeUpdate("sp_AddPlayMoneyLog", DBMgr.TexasPokerDB, gameRoom.MaxBindUserId, gameRoom.getUser(gameRoom.MaxBindSeatId).AccountId, room.maxBlind, 0);
		gameRoom.stake = gameRoom.callChip(gameRoom.MaxBindSeatId);
		gameDao.addGameLog(gameRoom,room.gameId(), room.step(), userMax, room.SNAPCARDS().value(), 0, room.maxBlind, room.curSeatChip(userMax.seatId), room.curSeatTotalChip(userMax.seatId), "大盲+" + room.maxBlind);
		if (userMin.stake <= 0) {
			gameRoom.allinCount++;
		}
		if (userMax.stake <= 0) {
			gameRoom.allinCount++;
		}
	}

	/**
	 * 下注,通知下一次操作人
	 * 
	 * @param cmdObject
	 */
	public static boolean operationNext(int roomId, BaseCommandObject cmdObject) {
		return GamePool.operationNext(RoomMgr.roomsMap.get(roomId), cmdObject);
	}

	/**
	 * 广播，将游戏生成的牌发给房间所有人
	 * 
	 * @param cmdObject
	 * @return
	 */
	public static boolean broadcastStartGame(BaseCommandObject cmdObject, int roomid) {
		Log.info("=========新游戏即将开始=============");
		if (startGame(roomid, cmdObject.dbIndex)) {
			RoomConfigItem room = RoomMgr.getRoom(roomid);
			room.GameSeatLock().lock();
			try {
				UserInfoEntity user;// = cmdObject.getUser();
				cmdObject.setCmd(Protocol.StartGameCmd);// Step 2:
				// DataPacket dataPacket = new DataPacket(Protocol.StartGameCmd);
				cmdObject.writeBegin();
				cmdObject.writeInt(room.dealer());
				int card1position = cmdObject.position();
				cmdObject.writeString("1h");
				cmdObject.writeString("2h");
				cmdObject.writeInt(room.gameUsersSize());
				// 游戏开始，发手牌
				// SessionObject[] seatUsers = room.seatUsers();
				// List<Integer> userSeats = room.userSeats();
				com.wandian.util.ArrayList<SessionObject> gameSessions = room.GameSessions();
				ArrayList<SessionObject> roomSessions = room.roomUsers();
				//				Log.debug(String.format("[StartGame]当前房间%s游戏开始,坐位上人数%s", room.id, gameSessions.size()));
				for (int i = 0; i < gameSessions.size(); i++) {
					user = gameSessions.get(i).getUser();
					cmdObject.writeInt(user.seatId);
					cmdObject.writeFloat(room.callChip(user.seatId));
				}
				// while (i < room.roomSeatSize()) {
				// user = room.seatUserByIndex(i);;
				// dataPacket.writeInt(user.seatId);
				// dataPacket.writeInt(room.callChip(user.seatId));
				// i++;
				// }
				cmdObject.writeEnd();
				for (SessionObject session : roomSessions) {
					user = session.getUser();
					cmdObject.position(card1position);
					if (user.card1.length() != 2) {
						cmdObject.writeString("--");
						cmdObject.writeString("--");
					} else {
						cmdObject.writeString(user.card1);
						cmdObject.writeString(user.card2);
					}
					//Log.debug(String.format("[StartGame]当前房间%s游戏开始,给坐位%s玩家%s发牌%s %s 下注%s", room.id, user.nickName, user.seatId, user.card1, user.card2, room.callChip(user.seatId)));
					cmdObject.position(0);
//					UserMgr.I().SendData(session, cmdObject);
				}
				return true;
			} finally {
				room.GameSeatLock().unlock();
			}
		} else {
			//Log.debug("broadcastStartGame游戏人数不够或其他原因,未能触发游戏开始");
			return false;
		}
	}

	/**
	 * 游戏结束三部曲
	 * 
	 * @param room
	 * @param cmdObject
	 * @throws InterruptedException
	 */
	/*public static void GameOver(RoomConfigItem room, BaseCommandObject cmdObject, boolean showCard, int dbIndex) throws InterruptedException {
		// 分配边池
		Log.debug("游戏结束显示底池");
		ShowBonusPool(room, cmdObject);
		room.CalculateWinner(dbIndex);
		// 中心服务器允许使用积宝，并且积宝在本局已使用
		if (room.isAllowCornucopia && room.isUsingCornucopia) {
			if (room.gameRoom.addCornucopiaSuc && room.gameRoom.Cornucopias.size() > 0) {
				// 新建一个命令，去与中心服务器通信，告诉产生了积宝，同时发送更新当前积宝到客户端
				// room.delay(1000, TimeUnit.MILLISECONDS);
				// room.startTimer(GameData.CMD_CORNUCOPIA);
				CornucopiaEntity cornucopia = room.gameRoom.Cornucopias.get(0);
				GameServer.requestor.requestSendCornucopia(true, room.cornucopiaCallBack, room.cornucopiaCardType, room.id, cornucopia.SeatId, cornucopia.UserId,cornucopia.idx, cornucopia.NickName, cornucopia.MaxCards);
			} else {
				Log.error("中心服务器允许使用积宝，并且积宝在本局已使用,但是游戏结束却没有出现积宝牌");
			}
		} else {
			if (room.gameRoom.addCornucopiaSuc && room.gameRoom.Cornucopias.size() > 0) {
				Log.error("中心服务器不允许使用积宝或者积宝在本局已使用,但是游戏结束却出现积宝牌");
			}
		}
		if (showCard) {
			Log.debug("游戏结束显示底牌");
			CMD_SHOW(room, cmdObject);
			Sleep(1500);
		}
		Log.debug("游戏结束显示赢家");
		CMD_POTS(room, cmdObject, 0);
		Sleep(2500);
		Log.debug("游戏结束通知");
		broadCastGameOver(room, cmdObject);
	}*/

	public static void SHOWCARD(RoomConfigItem room, BaseCommandObject cmdObject, boolean showCard, int dbIndex) {
		//		room.CalculateWinner(dbIndex);
		if (showCard) {
			Log.debug("游戏结束显示底牌");
			CMD_SHOW(room, cmdObject);
		}
	}

	private static void standUpNoStake(RoomConfigItem room, BaseCommandObject cmdObject) {
		// 如果在坐玩家的筹码不够，起立
		UserInfoEntity user;
		SessionObject session;
//		room.GameSeatLock().lock();
//		try {
		int seatId;
		for (int i = 0; i < room.gameRoom.gameOverLen; i++) {
			seatId = room.gameRoom.gameOverSeats[i];
			session = room.seatUsers(seatId);
			user = session.getUser();
			if (user == null || user.stake < room.maxBlind) {
				RoomMgr.sendStandup(session, cmdObject.dbIndex, cmdObject, true);
			}
		}
//		} catch (Exception e) {
//			room.GameSeatLock().unlock();
//		}

	}

	public static void broadCastGameOver(RoomConfigItem room, BaseCommandObject cmdObject) {
		// DataPacket dataPacket = new DataPacket(Protocol.CMD_GAME_OVER);
		cmdObject.setCmd(Protocol.CMD_GAME_OVER);
		cmdObject.writeBegin();
		cmdObject.writeEnd();
//		UserMgr.I().broadCastToRoomUsers(room, cmdObject);
		room.curSeatId(0);
		room.reset();
		standUpNoStake(room, cmdObject);
		// room.reset();
		room.isPlaying(false);
		room.doingGameOver(false, 0);
	}

	/**
	 * 下注,通知下一次操作人 ,Step1 合法性检查 Step2,取得当前人,
	 * 
	 * @param cmdObject
	 */
	public static boolean operationNext(RoomConfigItem room, BaseCommandObject cmdObject) {
		if (!checkOperateValid(room)) {
			return false;
		}
		room.operateStep();
		UserInfoEntity user = findNextOperator(room);
		CMD_OPERATION_NEXT(room, cmdObject, user);
		return true;
	}

	private static boolean checkOperateValid(RoomConfigItem room) {
		// Step 1 合法性检查
		if (room == null) {
			Log.debug(String.format("[GamePool]操牌开始失败,房间为null"));
			return false;
		}
		if (room.curSeatId() < 1) {
			Log.debug(String.format("[GamePool]操牌开始失败,curSeatId<0"));
			return false;
		}
		return true;
	}

	private static UserInfoEntity findNextOperator(RoomConfigItem room) {
		UserInfoEntity user = null; // room.nextUser();
		// Step2 ,找当前操牌者,必须符合条件
		int find = 0;
		while (true) {
			find++;
			if (find > 10) {
				Log.error("什么破代码,找了9个座位都找不到合适的出牌的人");
				break;
			}
			user = room.nextUser();
			// 弃牌，全压的跳过
			if (!room.containGameUser(user) || user.lastAction == LastAction.FOLD || user.lastAction == LastAction.ALLIN) {
				continue;
			} else {
				//				Log.debug(String.format("[operationNext]房间%s,Step %s seatid %s user %s 出牌,找到下一个合适出牌者，总共找了%s次", room.id, room.step(), room.curSeatId(), user.nickName, find));
				break;
			}
		}
		return user;
	}

	private static void CMD_OPERATION_NEXT(RoomConfigItem room, BaseCommandObject cmdObject, UserInfoEntity user) {
		if (user.seatId < 1 || user.roomId < 1)
			return;
		// Step3 找到当前用户的5个操数据
		// 如果玩家不是弃牌,玩家身上的下注与本回的比较，得到最小minCall,
		// int minCall = room.stake() - user.callChip();// save in game
		// room.minCall(room.stake() - user.callChip())
		// room.minCall(room.stake() - user.callChip());
		// 如果是加注,最小加一个默认值如,大盲注*2, room.stake()*2
		if (room.stake() == 0) {
			room.minRaise(room.MaxBind() * 2);
		} else {
			room.minRaise(room.stake() * 2);// 如果先前玩家callChip>0,MinRaise为2*callChip.第一个callchip最小就是大盲的两倍
		}
		if (room.minRaise() >= user.stake) {
			room.minRaise(user.stake);
		}
		// 如果是最大加注，应该是多少：非弃牌,除自己之外的玩家全部stake(筹码)maxStake-当前玩家已下的筹码seatChip,不能大于自身的全部
		room.maxRaise(room.getSeatMaxRaise(user.seatId));
		// Step 4.广播房间组
		// DataPacket dataPacket = new DataPacket(Protocol.CMD_OPERATION_NEXT);
		cmdObject.setCmd(Protocol.CMD_OPERATION_NEXT);
		cmdObject.writeBegin();
		cmdObject.writeInt(room.step());
		cmdObject.writeInt(room.curSeatId());
		float minCall = 0;
		if (room.stake() > room.callChip(user.seatId)) {
			minCall = room.stake();// - room.callChip(user.seatId);
		}
		if (room.minRaise() < minCall) {
			room.minRaise(minCall);
		}
		if (room.minRaise() > room.maxRaise()) {
			room.minRaise(room.maxRaise());
		}
		room.minCall(minCall);
		cmdObject.writeFloat(room.minCall());
		cmdObject.writeFloat(room.maxRaise());
		cmdObject.writeFloat(room.minRaise());
		cmdObject.writeFloat(user.stake);//
		cmdObject.writeEnd();
//		UserMgr.I().broadCastToRoomUsers(room.id, cmdObject);
		//		Log.debug(String.format("[GamePool]操牌开始成功 Step:%s,当前坐位:%s操作,最小叫%s 最大加注%s, 最小加注%s ,筹码%s", room.step(), room.curSeatId(), minCall, room.maxRaise(), room.minRaise(), user.stake));
		// Step 5，定时器任务，检测超时
//		room.delay(14, TimeUnit.SECONDS);
//		room.startTimer(GameData.TIMERTOFOLD, room.id, cmdObject, user);
	}

	/**
	 * 下注,通知下一次操作人
	 * 
	 * @param cmdObject
	 */
	public static void OPERATION_SUCC(/* BaseCommandObject cmdObject */) {

		// objData.seatId=this._socket.readInt();
		// objData.stake=this._socket.readUInt();
		// objData.callChip=this._socket.readUInt();
		// objData.lastAction=this._socket.readInt();
	}

	public static boolean leftOneOperate(RoomConfigItem room) {
		int find = 0;
		UserInfoEntity user;
		int curSeatId = room.curSeatId();
		int tempSeatId = curSeatId;
		while (true) {
			find++;
			if (find > 10) {
				Log.error("什么破代码,找了9个座位都找不到合适的出牌的人");
				break;
			}
			user = room.getNextUser(tempSeatId);
			tempSeatId = user.seatId;
			// 弃牌，全压的跳过
			if (user.lastAction != LastAction.FOLD && user.lastAction != LastAction.ALLIN && room.containGameUser(user)) {
				break;
			}
			if (user.seatId == curSeatId)
				break;
		}
		return tempSeatId == curSeatId;
	}

	public static boolean localRobot = true;

	/**
	 * 玩家下注操作请求,Step 1处理下注,Step 2,将处理结果发回给玩家, Step
	 * 3,检查第几回是否结束,判断所有玩家下注是否一样(Allin可以少)若游戏结束，跳往step6 Step4,通知下一个操作人
	 * Step5,保存操作记录 Step,6 广播结束,保存游戏结束日志 ,Step 7,若第6步成功,则重新判断开始游戏
	 * 
	 * @param cmdObject
	 */
	public static void CMD_OPERATION_REQUEST(boolean isTimeFold, int roomId, BaseCommandObject cmdObject, UserInfoEntity timeUser) {
		RoomConfigItem room = RoomMgr.getRoom(roomId);
		if (room == null) {
			Log.info("《《========游戏退出:" + room.curSeatId() + " step:" + room.step());
			return;
		}
		UserInfoEntity user = setGiveChip(isTimeFold, room, cmdObject, timeUser);
		if (user == null) {
			Log.info("《《========游戏退出:" + room.curSeatId() + " step:" + room.step());
			return;
		}
		CMD_OPERATION_SUCC(room, cmdObject, user, room.getLeftTime(), room.giveChip(), room.memo());
		boolean isGameOver = room.isGameOver();
		if (isGameOver) {
			try {
				GameOverByLeftOneOrAllIn(room, cmdObject, room.boolShowCard());
			} catch (Exception e) {
				Log.error(e);
				e.printStackTrace();
			}

			return;
		}
		boolean showResult = false;
		//当前房间的最大筹码对于下一个操作人的筹码，同时该人下过注
		UserInfoEntity nextUser = getNextOperate(room);
		if (room.callChip(nextUser.seatId) == room.stake() && room.userStep(nextUser.seatId) > 0) {
			showResult = true;
		}
		// Step3检查第几回是否结束,判断所有玩家下注是否一样(Allin可以少), 如果已回结束,翻牌……
		/*int maxRaiserSeatId = room.maxRaiseSeatId();
		UserInfoEntity maxuser = room.getUser(maxRaiserSeatId);
		if (user == null || !room.containGameUser(maxuser) || maxuser.lastAction == 2) {
			if (room.resetStandMaxRaiser() == 0) {
				if (room.isGameOver())
					GameOverByLeftOneOrAllIn(room, cmdObject, room.boolShowCard());
				return;
			}
		}
		UserInfoEntity nextUser = getNextOperate(room);
		if (nextUser == null) {
			GameOverByLeftOneOrAllIn(room, cmdObject, false);
			return;
		}
		if (maxuser.stake == 0) {
			if (nextUser.seatId > room.curSeatId() || nextUser.seatId < maxRaiserSeatId) {
				showResult = false;
			} else {
				showResult = true;
			}
		} else {
			if (maxRaiserSeatId == nextUser.seatId && room.userStep(maxRaiserSeatId) > 0)
				showResult = true;
		}*/
		setGameStatus(room, cmdObject, showResult);
		if (room.SNAPCARDS() != SNAPCARDS.GAME_OVER) {
			if (!showResult) {
				if (operationNext(room, cmdObject)) {
					Log.info("=========操作下一个成功=============当前坐位:" + room.curSeatId() + " user" + nextUser.userName + " RoundNum:" + room.SNAPCARDS().value());
					Test.doOperationNext(room, cmdObject);
				}
//				room.delay(200, TimeUnit.MILLISECONDS);// 15秒
//				room.startTimer(GameData.TIMERTOOPERATIONNEXT, room, cmdObject);
				// Sleep(100);
				// GamePool.operationNext(room, cmdObject);
			} else {
				// 如果翻牌了,留一个段时间给客户端，在显示当前倒计时
				// room.delay(8);
				// room.startTimer(GameData.TIMERTOOPERATIONNEXT, room.id,
				// cmdObject, user);
				// ShowBonusPool(room, cmdObject);
				room.clearUserStep();
				ShowBonusPool(room, cmdObject);
				if (operationNext(room, cmdObject)) {
					Log.info("=========操作下一个成功=============当前坐位:" + room.curSeatId() + " user" + nextUser.userName);
					Test.doOperationNext(room, cmdObject);
				}
//				TIMERSHOWBONUSPOOL(room, cmdObject, false, false, cmdObject.dbIndex);
				// GamePool.operationNext(room, cmdObject);
			}
		} else {
			//			TIMERSHOWBONUSPOOL(room, cmdObject, true, true, cmdObject.dbIndex);
			room.boolShowCard(true);
			GameOverByLeftOneOrAllIn(room, cmdObject, true);
			// GameOverAndStartNew(room, cmdObject, true);
			return;
		}
	}

	//通过user设置传递是否下注成功
	private static UserInfoEntity setGiveChip(boolean isTimeFold, RoomConfigItem room, BaseCommandObject cmdObject, UserInfoEntity timeUser) {
		// Step 1 检查请求是来自客户端还是定时器,如果不是来自定时器，检查本次请求是不是当前坐位,不是拒绝
		float chipMoney = 0;
		// 默认是定时器的玩家, cmdObject.getUser();
		UserInfoEntity user;
		if (!isTimeFold) {
			// Step1-1判断超时,当前坐位已不是该坐位
			user = cmdObject.getUser();
			if (user != room.getUser(room.curSeatId())) {
				Log.debug("[CMD_OPERATION_REQUEST]收到玩家超时请求!");
				return null;
			}
			// 如果当前坐位等于该坐位,则取消定时器
			room.cancel();
			// 读取客户端的数据
			room.gameRoom.AccepStep = cmdObject.readInt();
			user.lastAction = cmdObject.readInt();
			chipMoney = cmdObject.readFloat();
		} else {
			user = timeUser;
			user.lastAction = LastAction.FOLD;// 定时器默认是放弃
			// 定时器没有取消。在这里干掉
			if (room.boolCanncel() || user.lastAction == 2) {
				Log.debug("定时器再次执行了.但该定时器已被用户操作取消，所以，在这里pass");
				return null;
			}
		}
		room.GameUser(user.seatId - 1).lastAction = user.lastAction;
		room.stepUser(user.seatId);
		// 如果不是加注
		// 设置当前玩家的lastaction
		// 如果是allin,callChip(user.stake)

		room.stepMemo(user.nickName);
		// boolean boolFoldOver = false;
		// Step 1-1
		// int giveChip=0;
		switch (user.lastAction) {
		case 1:// LastAction.CHECK.value():
			room.stepMemoContact(" 看牌");
			room.giveChip(0);
			break;
		case 2:// LastAction.FOLD:
			room.stepMemoContact(" 弃牌");
			room.giveChip(0);
			room.addFoldCount();
			if (user.seatId == room.maxRaiseSeatId()) {
				//				Log.debug("当前MaxRaise放弃了" + user.seatId);
				room.resetStandMaxRaiser();
				//				Log.debug("当前MaxRaise换成" + room.maxRaiseSeatId());
			}
			if (user.seatId == room.maxStakeSeat()) {
				room.setMaxStake();
			}
			// boolFoldOver = room.addFold();
			break;
		case 3:// LastAction.CALL.value():
			room.giveChip(room.stake() - room.callChip(user.seatId));
			room.callChip(user.seatId, room.giveChip());
			gameRoomDao(cmdObject.dbIndex).executeUpdate("sp_AddPlayMoneyLog", DBMgr.TexasPokerDB, user.userId, user.AccountId, room.giveChip(), 0);
			// user.stake -= minChip;
			if (user.stake <= 0) {
				user.lastAction = LastAction.ALLIN;
				room.GameUser(user.seatId - 1).lastAction = LastAction.ALLIN;
				room.stepMemoContact(" 全押" + room.giveChip());
				room.addAllInCount();
			} else {
				room.stepMemoContact(" 跟注" + room.giveChip());
			}
			break;
		case 4:// LastAction.RAISE.value():
				// if (minChip > chipMoney) {
				// Log.error(String.format(
				// "加注出现严重逻辑错误,加注的金额%s不应该小于最小喊注%s,一般情况，加注应该是两倍的最小",
				// chipMoney, minChip));
				// }
			if (chipMoney > room.stake()) {
				//				Log.debug("[加注]最大加注者改变前," + room.maxRaiseSeatId());
				room.maxRaiseSeatId(user.seatId);
				//放在giveChip里判断
//				room.stake(chipMoney);
				//				Log.debug("[加注]最大加注者改变后," + room.maxRaiseSeatId());
			}
			room.giveChip(chipMoney - room.callChip(user.seatId));
			// room.callChipTo(user.seatId, chipMoney);
			room.callChip(user.seatId, room.giveChip());
			gameRoomDao(cmdObject.dbIndex).executeUpdate("sp_AddPlayMoneyLog", DBMgr.TexasPokerDB, user.userId, user.AccountId, room.giveChip(), 0);
			// user.stake -= addChip;
			// room.stake(chipMoney);//当前最大筹码变
			if (user.stake == 0) {
				user.lastAction = LastAction.ALLIN;
				room.GameUser(user.seatId - 1).lastAction = LastAction.ALLIN;
				room.stepMemoContact(" 全押" + room.giveChip());
				room.addAllInCount();
			} else {
				room.stepMemoContact(" 加注" + room.giveChip());
			}
			break;
		case 5:// LastAction.ALLIN:
				// 计算边池，若玩家超过此值,重新分配池
			room.giveChip(user.stake);
			room.stepMemoContact(" 全押" + user.stake);
			room.callChip(user.seatId, user.stake);
			if (room.callChip(user.seatId) > room.stake()) {
				//				Log.debug("[AllIn]最大加注者改变前," + room.maxRaiseSeatId());
				room.maxRaiseSeatId(user.seatId);
				room.stake(room.callChip(user.seatId));
				//				Log.debug("[AllIn]最大加注者改变后," + room.maxRaiseSeatId());
			}
			room.addAllInCount();
			user.stake = 0;
			gameRoomDao(cmdObject.dbIndex).executeUpdate("sp_AddPlayMoneyLog", DBMgr.TexasPokerDB, user.userId, user.AccountId, room.giveChip(), 0);
			break;
		default:
			break;
		}
		user.totalChip += room.giveChip();
		// 改变房间筹码
		if (room.callChip(user.seatId) > room.stake()) {
			room.stake(room.callChip(user.seatId));
		}
		return user;
	}

	private static void setGameStatus(RoomConfigItem room, BaseCommandObject cmdObject, boolean showResult) {
		switch (room.SNAPCARDS()) {
		case SNAPCARDS_START:// [大盲左边开始->到大盲结束(最大加注者),]未翻牌前--->翻牌:每个玩家都需要点一次按钮,并且除弃牌之外的玩家,所有玩家下注必须相等(allin者若下注少了可以允许)[最大加注玩家右侧]Step1
								// 翻牌
			if (showResult) {
				room.currPublicCardLen(3);
				room.resetMaxRaiseSeat();
				CMD_SNAPCARDS_FLOP(room, cmdObject);
				Log.info("<<<<<<<<翻牌===============================");
			}
			break;
		case SNAPCARDS_FLOP:// [小盲注开始(若不在,顺时针推)->庄家结束(如不在,到了小盲注（最大加注者）,转牌)]Step2到小盲注就检查是否结束
			if (showResult) {
				room.currPublicCardLen(4);
				room.resetMaxRaiseSeat();
				CMD_SNAPCARDS_TURN(room, cmdObject);
				Log.info("<<<<<<<<转牌===============================");
			}
			break;
		case SNAPCARDS_TURN:
			if (showResult) {
				room.currPublicCardLen(5);
				room.resetMaxRaiseSeat();
				CMD_SNAPCARDS_RIVER(room, cmdObject);
				Log.info("<<<<<<<<河牌===============================");
			}
			break;
		case SNAPCARDS_RIVER:
			if (showResult) {
				// Step 3-1 发3牌
				room.SNAPCARDS(SNAPCARDS.GAME_OVER);
				Log.info("<<<<<<<<游戏结束===============================");
			}
			break;
		default:
			break;
		}
	}

	private static UserInfoEntity getNextOperate(RoomConfigItem room) {
		UserInfoEntity nextUser = null;
		int tempSeatId = room.curSeatId();
		int find = 0;
		while (true) {
			find++;
			if (find > 10) {
				Log.error("什么破代码,找了9个座位都找不到合适的出牌的人");
				break;
			}
			nextUser = room.getNextUser(tempSeatId);
			// 弃牌，全压的跳过
			if (!room.containGameUser(nextUser) || nextUser.lastAction == LastAction.FOLD || nextUser.lastAction == LastAction.ALLIN) {
				tempSeatId = nextUser.seatId;
				nextUser = null;
				continue;
			} else {
				break;
			}
		}
		return nextUser;
	}

	/**
	 * 形成边池定时器
	 * 
	 * @param room
	 * @param cmdObject
	 * @param boolGameOver
	 * @param showCard
	 * @param dbIndex
	 */
	private static void TIMERSHOWBONUSPOOL(RoomConfigItem room, BaseCommandObject cmdObject, boolean boolGameOver, boolean showCard, int dbIndex) {
		room.delay(1000, TimeUnit.MILLISECONDS);
		room.putTimerParams("BoolGameOver", boolGameOver);
		room.putTimerParams("ShowCard", showCard);
		room.putTimerParams("DbIndex", dbIndex);
		room.startTimer(GameData.SHOWBONUSPOOL, room, cmdObject);
	}

	private static void CMD_OPERATION_SUCC(RoomConfigItem room, BaseCommandObject cmdObject, UserInfoEntity user, int leftTime, float giveChip, String memo) {
		// Step 2
		cmdObject.setCmd(Protocol.CMD_OPERATION_SUCC);
		cmdObject.writeBegin();
		cmdObject.writeInt(user.seatId);
		cmdObject.writeFloat(user.stake);
		cmdObject.writeFloat(room.callChip(user.seatId));
		cmdObject.writeInt(user.lastAction);
		cmdObject.writeEnd();
//		UserMgr.I().broadCastToRoomUsers(room, cmdObject);
		// Step5,保存Step记录，换成存储过程
		DaoManager.GameRoomDao(cmdObject.dbIndex).addGameLog(room.gameRoom,room.gameId(), room.step(), user, room.SNAPCARDS().value(), leftTime, giveChip, room.curSeatChip(user.seatId), room.curSeatTotalChip(user.seatId), memo);
	}

	/**
	 * 定时器方式结束游戏,游戏结束的入口函数
	 * 
	 * @param room
	 * @param cmdObject
	 * @param boolShowCard
	 */
	public static void GameOverByLeftOneOrAllIn(RoomConfigItem room, BaseCommandObject cmdObject, boolean boolShowCard) {
		if (!room.isPlaying() || room.doingGameOver()) {
			Log.info("《《========游戏退出:error:房间未开始或正在doingGameOver" + room.curSeatId() + " step:" + room.step());
			return;
		}
		Log.info("========游戏正在准备结束游戏…………" + room.curSeatId() + " step:" + room.step());
		room.boolShowCard(boolShowCard);
		room.doingGameOver(true, cmdObject.dbIndex);
		ShowBonusPool(room, cmdObject);
		SHOWCARD(room, cmdObject, boolShowCard, cmdObject.dbIndex);
		int potLen = room.BonusPoolsSize();
		for (int i = 0; i < potLen; i++) {
			CMD_POTS(room, cmdObject, i);
		}
		broadCastGameOver(room, cmdObject);
		if (!TestGamePool.isHistory)
			STARTNEWGAME(room, cmdObject);
		/*room.delay(1000, TimeUnit.MILLISECONDS);
		room.putTimerParams("BoolGameOver", true);
		room.putTimerParams("ShowCard", boolShowCard);
		room.putTimerParams("DbIndex", cmdObject.dbIndex);
		if (boolShowCard) {
			switch (room.SNAPCARDS()) {
			case SNAPCARDS_START:// [大盲左边开始->到大盲结束(最大加注者),]未翻牌前--->翻牌:每个玩家都需要点一次按钮,并且除弃牌之外的家,所有玩家下注必须相等(allin者若下注少了可以允许)[最大加注玩家右侧]Step1
				room.startTimer(GameData.CMD_SNAPCARDS_FLOP, room, cmdObject);
				break;
			case SNAPCARDS_FLOP:// [小盲注开始(若不在,顺时针推)->庄家结束(如不在,到了小盲注（最大加注者）,转牌)]Step2到小盲注就检查是否结束
				room.startTimer(GameData.CMD_SNAPCARDS_TURN, room, cmdObject);
				break;
			case SNAPCARDS_TURN:
				room.startTimer(GameData.CMD_SNAPCARDS_RIVER, room, cmdObject);
				break;
			case SNAPCARDS_RIVER:
				room.SNAPCARDS(SNAPCARDS.GAME_OVER);
				room.startTimer(GameData.SHOWBONUSPOOL, room, cmdObject);
				break;
			default:
				room.startTimer(GameData.SHOWBONUSPOOL, room, cmdObject);
				break;
			}
		} else {
			TIMERSHOWBONUSPOOL(room, cmdObject, true, false, cmdObject.dbIndex);
		}*/
	}

	/*private static void GameOverByAllIn(RoomConfigItem room, BaseCommandObject cmdObject, boolean b) {
		switch (room.SNAPCARDS()) {
		case SNAPCARDS_START:
			CMD_SNAPCARDS_FLOP(room, cmdObject);
			CMD_SNAPCARDS_TURN(room, cmdObject);
			CMD_SNAPCARDS_RIVER(room, cmdObject);
			room.SNAPCARDS(SNAPCARDS.GAME_OVER);
			break;
		case SNAPCARDS_FLOP:
			CMD_SNAPCARDS_TURN(room, cmdObject);
			CMD_SNAPCARDS_RIVER(room, cmdObject);
			room.SNAPCARDS(SNAPCARDS.GAME_OVER);
			break;
		case SNAPCARDS_TURN:
			CMD_SNAPCARDS_RIVER(room, cmdObject);
			room.SNAPCARDS(SNAPCARDS.GAME_OVER);
			break;
		case SNAPCARDS_RIVER:
			room.SNAPCARDS(SNAPCARDS.GAME_OVER);
			break;
		default:
			break;
		}
		GameOverAndStartNew(room, cmdObject, true);
	}*/

	/*public static void Sleep(int delay) {
		try {
			TimeUnit.MILLISECONDS.sleep(delay);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}*/

	/*public static void GameOverAndStartNew(RoomConfigItem room, BaseCommandObject cmdObject, boolean showCard) {
		//
		// Step2 通知游戏结束
		// step3 开始新游戏
		try {
			room.clearUserStep();
			GamePool.GameOver(room, cmdObject, showCard, cmdObject.dbIndex);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}// 游戏结束之后，马上开始下一把
		if (GamePool.broadcastStartGame(cmdObject, room.id)) {
			GamePool.operationNext(room, cmdObject);
		}
	}*/

	public static void STARTNEWGAME(RoomConfigItem room, BaseCommandObject cmdObject) {
		if (broadcastStartGame(cmdObject, room.id)) {
			Log.info("=========新游戏开始成功=============gameid:" + room.gameId());
			if (operationNext(room, cmdObject)) {
				Log.info("=========操作下一个成功=============当前坐位:" + room.curSeatId() + " RoundNum:" + room.SNAPCARDS().value());
				Test.doOperationNext(room, cmdObject);
			}
		} else {
			Log.info("=========新游戏开始失败=============");
		}
	}

	/**
	 * 显示边池
	 * 
	 * @param room
	 * @param cmdObject
	 */
	public static void ShowBonusPool(RoomConfigItem room, BaseCommandObject cmdObject) {
		//游戏结束,doingGameOver处入了池，并且清除了桌上chip
//		room.InBonusPool();
		room.clearSeatChip();
		CMD_CUR_POT(room, cmdObject);
		room.stake(0);
		//		Log.debug("当前指针重新设为庄家:" + room.dealer());
		room.curSeatId(room.dealer());
		// Step3-3 重置游戏参数,maxRaiser SeatId小盲(Raiser)->

	}

	public static void CMD_SNAPCARDS_FLOP(RoomConfigItem room, BaseCommandObject cmdObject) {
		// Step 3-1 发3牌
		cmdObject.setCmd(Protocol.CMD_SNAPCARDS_FLOP);
		cmdObject.writeBegin();
		cmdObject.writeString(room.PublicCards()[0]);
		cmdObject.writeString(room.PublicCards()[1]);
		cmdObject.writeString(room.PublicCards()[2]);
		cmdObject.writeEnd();
//		UserMgr.I().broadCastToRoomUsers(room, cmdObject);
		room.SNAPCARDS(SNAPCARDS.SNAPCARDS_FLOP);
	}

	public static void CMD_SNAPCARDS_TURN(RoomConfigItem room, BaseCommandObject cmdObject) {
		// Step 3-1 发3牌
		cmdObject.setCmd(Protocol.CMD_SNAPCARDS_TURN);
		cmdObject.writeBegin();
		cmdObject.writeString(room.PublicCards()[3]);
		cmdObject.writeEnd();
//		UserMgr.I().broadCastToRoomUsers(room, cmdObject);
		room.SNAPCARDS(SNAPCARDS.SNAPCARDS_TURN);
	}

	public static void CMD_SNAPCARDS_RIVER(RoomConfigItem room, BaseCommandObject cmdObject) {
		// Step 3-1 发3牌
		cmdObject.setCmd(Protocol.CMD_SNAPCARDS_RIVER);
		cmdObject.writeBegin();
		cmdObject.writeString(room.PublicCards()[4]);
		cmdObject.writeEnd();
//		UserMgr.I().broadCastToRoomUsers(room, cmdObject);
		room.SNAPCARDS(SNAPCARDS.SNAPCARDS_RIVER);
	}

	/**
	 * 第%NUM%边池形成
	 */
	public static void CMD_CUR_POT(RoomConfigItem room, BaseCommandObject cmdObject) {
		int potLen = room.BonusPoolsSize();
		int realLen = 0;
		for (int i = 0; i < potLen; i++) {
			if (room.bonusPool(i) > 0) {
				realLen++;
			}
		}
		cmdObject.setCmd(Protocol.CMD_CUR_POT);
		cmdObject.writeBegin();
		cmdObject.writeInt(realLen);
		for (int i = 0; i < potLen; i++) {
			if (room.bonusPool(i) == 0) {
				continue;
			}
			cmdObject.writeInt(i);
			cmdObject.writeFloat(room.bonusPool(i));
		}
		cmdObject.writeEnd();
//		UserMgr.I().broadCastToRoomUsers(room, cmdObject);
	}

	/**
	 * 显示底牌,放弃的牌不显示 <br/>
	 * 显示完牌动画，播放获胜画面
	 */
	public static void CMD_SHOW(RoomConfigItem room, BaseCommandObject cmdObject) {
		cmdObject.setCmd(Protocol.CMD_SHOW);
		cmdObject.writeBegin();
		UserGameEntity user;
		// Step1 ,写继续玩的玩家底牌
		int playerNum = 0;
		cmdObject.writeInt(playerNum);
		for (int i = 0; i < 9; i++) {
			user = room.GameUser(i);
			if (user != null && user.lastAction != LastAction.FOLD) {
				cmdObject.writeInt(user.seatId);
				cmdObject.writeInt(user.isWin);
				cmdObject.writeString(user.cards[0]);
				cmdObject.writeString(user.cards[1]);
				cmdObject.writeInt(user.cardType());
				playerNum++;
			}
		}
		int curPosition = cmdObject.position();
		cmdObject.position(0);
		cmdObject.writeInt(playerNum);
		//		Log.debug("Show牌的玩家数" + playerNum);
		cmdObject.position(curPosition);
		// 写赢的牌数组
		//		ArrayList<UserGameEntity> allWinners = room.allWinners();
		cmdObject.writeInt(room.allWinnersLen());
		//		Log.debug("Show牌的赢家数" + allWinners.size());
		for (int i = 0; i < 9; i++) {
			user = room.allWinners()[i];
			if (user != null) {
				cmdObject.writeInt(user.seatId);
				for (int j = 0; j < 5; j++) {
					cmdObject.writeString(user.getMaxHandcard().getCard(j));
					//					Log.debug(user.getMaxHandcard().getCard(j));
				}
			}
		}
		/*Iterator<UserGameEntity> it = allWinners.iterator();
		while (it.hasNext()) {
			user = it.next();
			//			Log.debug(user.user.nickName + "的最大手牌！");
			cmdObject.writeInt(user.seatId);
			for (int i = 0; i < 5; i++) {
				cmdObject.writeString(user.getMaxHandcard().getCard(i));
				Log.debug(user.getMaxHandcard().getCard(i));
			}
		}*/
		cmdObject.writeEnd();
//		UserMgr.I().broadCastToRoomUsers(room, cmdObject);
	}

	/**
	 * 广播当前房间,中聚宝盆
	 * 
	 * @param room
	 * @param cmdObject
	 */
	public static void CMD_REWARD_CORNUCOPIA(RoomConfigItem room, BaseCommandObject cmdObject) {
		ArrayList<CornucopiaEntity> cornucopias = room.gameRoom.Cornucopias;
		// 如果一场游戏出现多个获得积宝，程序需要调整
		if (cornucopias.size() > 1) {
			Log.error("kengdie~神马程序一场game出现了积宝人数" + cornucopias.size());
		}
		CornucopiaEntity cornucopia;
		for (int i = 0; i < cornucopias.size(); i++) {
			cornucopia = cornucopias.get(i);
			cmdObject.writeBegin();
			cmdObject.setCmd(Protocol.CMD_REWARD_CORNUCOPIA);
			cmdObject.writeInt(cornucopia.UserId);
			cmdObject.writeInt(cornucopia.idx);
			cmdObject.writeString(cornucopia.NickName);
			cmdObject.writeInt(cornucopia.CardType);
			cmdObject.writeFloat(cornucopia.WinMoney);
			cmdObject.writeInt(room.id);
			cmdObject.writeEnd();
//			UserMgr.I().broadCastToAllOnlines(cmdObject);
		}
	}

	/**
	 * 广播当前房间,中聚宝盆
	 * 
	 * @param room
	 * @param cmdObject
	 */
	public static void CMD_TESTREWARD_CORNUCOPIA(RoomConfigItem room, BaseCommandObject cmdObject) {
		cmdObject.writeBegin();
		cmdObject.setCmd(Protocol.CMD_REWARD_CORNUCOPIA);
		cmdObject.writeInt(1);
		cmdObject.writeString("test");
		cmdObject.writeInt(9);
		cmdObject.writeInt(10000);
		cmdObject.writeInt(room.id);
		cmdObject.writeEnd();
//		UserMgr.I().broadCastToAllOnlines(cmdObject);

	}

	/**
	 * 显示底牌,放弃的牌不显示 <br/>
	 * 显示完牌动画，播放获胜画面
	 */
	public static void CMD_POTS(RoomConfigItem room, BaseCommandObject cmdObject, int curPot) {
		int potLen = room.BonusPoolsSize();
		if (curPot >= potLen || room.bonusPool(curPot) <= 0)
			return;
		cmdObject.setCmd(Protocol.CMD_POTS);
		// 写赢的牌数组

		UserGameEntity[] winUser;
		UserGameEntity user;
		//		int i = curPot;
		// for (int i = 0; i < potLen; i++) {
		winUser = room.BonusWinner(curPot);
		if (winUser == null)// 家伙跑了
			return;
		// 不需要锁住
		cmdObject.writeBegin();
		cmdObject.writeInt(curPot);
		cmdObject.writeInt(winUser[0].cardType());
		cmdObject.writeInt(room.winnerMapLen(curPot));
		for (int j = 0; j < room.winnerMapLen(curPot); j++) {
			user = winUser[j];
			cmdObject.writeInt(user.seatId);
			cmdObject.writeInt(user.user.userId);
			cmdObject.writeFloat(user.bonusWin[curPot]);
			cmdObject.writeFloat(user.user.stake);
			if (room.boolShowCard()) {
				cmdObject.writeString(user.cards[0]);
				cmdObject.writeString(user.cards[1]);
				cmdObject.writeString(user.getCard(0));
				cmdObject.writeString(user.getCard(1));
				cmdObject.writeString(user.getCard(2));
				cmdObject.writeString(user.getCard(3));
				cmdObject.writeString(user.getCard(4));
			} else {
				cmdObject.writeString("-");
				cmdObject.writeString("-");
				cmdObject.writeString("-");
				cmdObject.writeString("-");
				cmdObject.writeString("-");
				cmdObject.writeString("-");
				cmdObject.writeString("-");
			}
			// cmdObject.writeString(user.maxHandcard[0]);
			// cmdObject.writeString(user.maxHandcard[1]);
			// cmdObject.writeString(user.maxHandcard[2]);
			// cmdObject.writeString(user.maxHandcard[3]);
			// cmdObject.writeString(user.maxHandcard[4]);
		}

		cmdObject.writeEnd();

//		UserMgr.I().broadCastToRoomUsers(room, cmdObject);
		// }

	}

	/**
	 * 计算牌类型
	 * 
	 * @param arrCards
	 * @return
	 */
	/*public static WinCardEntity countCardType(String[] arrCards, String[] handCards) {
		WinCardEntity cardTypeData2 = null;
		int total = arrCards.length;
		int index = 0;
		String cardStr = null;
		CardVo cardVo = null;
		ArrayList<ArrayList<CardVo>> arrHuase = new ArrayList<ArrayList<CardVo>>(4);
		for (int i = 0; i < 4; i++) {
			arrHuase.add(new ArrayList<CardVo>());
		}
		ArrayList<CardVo> arrCardVo = new ArrayList<CardVo>();
		while (index < total) {

			if (arrCards[index] == "-") {
				continue;
			} else {
				cardStr = arrCards[index];
				cardVo = new CardVo(cardStr);
				cardVo.num = countCardNum(cardStr.substring(0, 1));
				cardVo.huase = countCardHuaSe(cardStr.substring(1, 2));
				arrHuase.get(cardVo.huase - 1).add(cardVo);
				arrCardVo.add(cardVo);
				Collections.sort(arrHuase.get(cardVo.huase - 1));
			}
			index = index + 1;
		}
		// ---手牌
		for (String card : handCards) {
			if (card == "-") {
				continue;
			} else {
				cardVo = new CardVo(card);
				cardVo.num = countCardNum(card.substring(0, 1));
				cardVo.huase = countCardHuaSe(card.substring(1, 2));
				arrHuase.get(cardVo.huase - 1).add(cardVo);
				arrCardVo.add(cardVo);
				Collections.sort(arrHuase.get(cardVo.huase - 1));
			}
		}
		// ---
		Collections.sort(arrCardVo);
		// --------------同花5
		WinCardEntity cardTypeData = getFlush(arrHuase); // {type: 5, arr1:
															// copySameColor,
															// huase:
															// huaseIndex:1-4};

		// ---------顺子4,同花顺8|皇家同花顺9
		if (cardTypeData != null) {
			cardTypeData2 = cardTypeData;
			cardTypeData = getStraight(cardTypeData.arrCards, cardTypeData);
			if (cardTypeData != null) {
				return cardTypeData;
			}
		}
		// --------------四条7
		cardTypeData = getFourAkind(arrCardVo);
		if (cardTypeData != null) {
			return cardTypeData;
		}

		// 葫芦6,三条3,两对2,一对1,高牌0
		cardTypeData = getFullHouse(arrCardVo);
		if (cardTypeData.getType() == 6) {
			return cardTypeData;
		}
		if (cardTypeData2 == null) {
			// 顺子
			WinCardEntity shunziData = getStraight(arrCardVo, null);
			if (shunziData != null) {
				return shunziData;
			}
			return cardTypeData;
		} else {
			return cardTypeData2;
		}
	}*/

	/**
	 * 葫芦6,三条3,两对2,一对1,高牌0
	 * 
	 * @param arrCardVo
	 *            已排序的数组
	 * @return
	 */
	/*private static WinCardEntity getFullHouse(ArrayList<CardVo> arrCardVo) {
		CardVo tempCard = null;
		CardVo preCard = null;
		int arrLength = arrCardVo.size();
		ArrayList<ArrayList<CardVo>> arrSame = new ArrayList<ArrayList<CardVo>>();
		int index = 0;
		ArrayList<CardVo> tempArr = new ArrayList<CardVo>();
		while (index < arrLength) {
			// [3,3,3,1,2]
			tempCard = arrCardVo.get(index);
			if (index == 0) {
				tempArr.add(tempCard);
				arrSame.add(tempArr); // [[3,3,3],[1],[2]]
			} else {
				preCard = arrCardVo.get(index - 1);
				if (tempCard.num == preCard.num) {
					// if(arrSame.get(arrSame.size() - 1)==null){
					// arrSame.get(arrSame.size() - 1)=new ArrayList<CardVo>();
					// }
					arrSame.get(arrSame.size() - 1).add(tempCard);
				} else {
					ArrayList<CardVo> tempArr2 = new ArrayList<CardVo>();
					tempArr2.add(tempCard);
					arrSame.add(tempArr2);
				}
			}
			index = index + 1;
		}
		ArrayList<ArrayList<CardVo>> arrTwo = new ArrayList<ArrayList<CardVo>>();
		ArrayList<ArrayList<CardVo>> arrThree = new ArrayList<ArrayList<CardVo>>();
		index = 0;
		while (index < arrSame.size()) {

			if (arrSame.get(index).size() == 3) {
				arrThree.add(arrSame.get(index));
			} else if (arrSame.get(index).size() == 2) {
				arrTwo.add(arrSame.get(index));
			}
			index = index + 1;
		}
		int threeLen = arrThree.size();
		int twoLen = arrTwo.size();
		if (threeLen >= 1 && twoLen >= 1) {
			if (threeLen == 2) {
				arrThree.get(1).remove(0);
				return new WinCardEntity(6, arrThree.get(0), arrThree.get(1), arrCardVo);// {type:
																							// 6,
																							// arr1:
																							// arrThree[0],
																							// arr2:
																							// arrThree[1]};
			}
			// 葫芦
			return new WinCardEntity(6, arrThree.get(0), arrTwo.get(0), arrCardVo);// {type:
																					// 6,
																					// arr1:
																					// arrThree[0],
																					// arr2:
																					// arrTwo[0]};

		} else {
			if (threeLen == 1) // 三条
			{
				return new WinCardEntity(3, arrThree.get(0), null, arrCardVo);// {type:
																				// 3,
																				// arr1:
																				// arrThree[0]};
			}
			if (twoLen >= 2) // 两对
			{
				return new WinCardEntity(2, arrTwo.get(0), arrTwo.get(1), arrCardVo);// {type:
																						// 2,
																						// arr1:
																						// arrThree[0],
																						// arr2:
																						// arrTwo[1]};
			}
			if (twoLen == 1) // 一对
			{
				return new WinCardEntity(1, arrTwo.get(0), null, arrCardVo);// {type:
																			// 1,
																			// arr1:
																			// arrTwo[0]};
			}
			// 高牌
			// ArrayList<CardVo> highCard = new ArrayList<CardVo>();
			// highCard.add(arrCardVo.get(0));
			return new WinCardEntity(0, arrCardVo, null, arrCardVo);// {type: 0,
																	// arr1:
																	// [arrCardVo[0]]};
		}
	}*/

	/**
	 * 四条7
	 * 
	 * @param arrCardVo
	 * @return
	 */
	/*private static WinCardEntity getFourAkind(ArrayList<CardVo> arrCardVo) {
		CardVo tempCard = null;
		CardVo nextCard = null;
		CardVo singleCard = null;
		ArrayList<CardVo> arrSame = new ArrayList<CardVo>();
		int arrCardlen = arrCardVo.size();
		int index = 0;
		while (index < arrCardlen) {

			tempCard = arrCardVo.get(index);
			if ((index + 1) >= arrCardlen) {
				nextCard = arrCardVo.get(index - 1);
				if (tempCard.num == nextCard.num) {
					arrSame.add(tempCard);
				} else {
					singleCard = nextCard;
				}
				break;
			}
			nextCard = arrCardVo.get(index + 1);
			arrSame.add(tempCard);
			if (tempCard.num != nextCard.num) {
				if (arrSame.size() < 4) {
					arrSame.clear();
					singleCard = tempCard;
				} else {
					break;
				}
			}
			index = index + 1;
		}
		if (arrSame.size() == 4) {
			return new WinCardEntity(7, arrSame, null, arrCardVo, singleCard);// {type:
																				// 7,
																				// arr1:
																				// arrSame};
																				// //四条
		}
		return null;
	}*/

	/**
	 * //高牌0|一对1|两对2|三条3|顺子4|同花5|葫芦6|四条7|同花顺8|皇家同花顺9 <br/>
	 * 皇家同花顺9,同花顺8,顺子4
	 * 
	 * @param arrSomecolor
	 *            {"1h","2h","3h","4h","5h"}
	 * @param sameColorData
	 *            {type: 5, arr1: arrSomecolor, huase: huaseIndex:1-4};
	 * @return
	 */
	/*private static WinCardEntity getStraight(ArrayList<CardVo> arrSomecolor, WinCardEntity sameColorData) {
		CardVo cardVo = null;
		CardVo cardVo2 = null;
		CardVo tempCardVo = null;
		int sameLen = arrSomecolor.size();
		if (arrSomecolor.get(sameLen - 1).num == 1) {
			cardVo = new CardVo("A" + arrHuase[arrSomecolor.get(sameLen - 1).huase]);
			cardVo.num = 14;
			cardVo.huase = arrSomecolor.get(sameLen - 1).huase;
			arrSomecolor.add(cardVo);
			Collections.sort(arrSomecolor);
		}
		sameLen = arrSomecolor.size();
		ArrayList<CardVo> arrContinueCard = new ArrayList<CardVo>();
		int index = 0;
		while (index < sameLen) {

			cardVo2 = arrSomecolor.get(index);
			if (index == 0) {
				arrContinueCard.add(cardVo2);
			} else {
				// [5,4,4,3,2,1]
				tempCardVo = arrSomecolor.get((index - 1));
				// 后面的+1=前面的
				if ((cardVo2.num + 1) == tempCardVo.num) {
					arrContinueCard.add(cardVo2);
				}
				// 如果值相等，继续
				else if (cardVo2.num == tempCardVo.num) {
					index++;
					continue;
				}
				// arrContinueCard[5,4,3,2,1]
				else if (arrContinueCard.size() >= 5) {
					break;
				}
				// 前面的不符合，后面开始重新计算
				else {
					arrContinueCard.clear();
					arrContinueCard.add(cardVo2);
				}
			}
			index++;
		}
		arrSomecolor.remove(cardVo);
		if (arrContinueCard.size() >= 5) {
			if (sameColorData != null) {
				// 14是临时增加的
				if (arrContinueCard.get(0).num == 14) {
					arrContinueCard.remove(arrContinueCard.size() - 1);
					// 皇家同花顺
					return new WinCardEntity(9, sameColorData.huase, arrContinueCard, arrSomecolor);// {type:
																									// 9,
																									// arr1:
																									// arrContinueCard,
																									// huase:
																									// sameColorData.huase};
				}
				// 同花顺
				return new WinCardEntity(8, sameColorData.huase, arrContinueCard, arrSomecolor);// {type:
																								// 8,
																								// arr1:
																								// arrContinueCard,
																								// huase:
																								// sameColorData.huase};
			} else {
				// 顺子
				return new WinCardEntity(4, -1, arrContinueCard, arrSomecolor);// {type:
																				// 4,
																				// arr:
																				// arrContinueCard};
			}
		}
		return null;
	}*/

	/**
	 * 同花
	 * 
	 * @param arrHuase
	 *            [[{"1h","2h","3h","4h","5h"}],[],[],[]]
	 * @return
	 */
	/*private static WinCardEntity getFlush(WinCardEntity winCard,ArrayList<ArrayList<CardVo>> arrHuase) {
		int huaseLen = 0;
		ArrayList<CardVo> copySameColor = new ArrayList<CardVo>();
		int huaseIndex = 0;
		int index = 0;
		while (index < arrHuase.size()) {

			huaseLen = arrHuase.get(index).size();
			if (huaseLen >= 5) {
				huaseIndex = index + 1;
				// copySameColor.add();//huaseLen - 5, huaseLen);
				copySameColor.addAll(arrHuase.get(index).subList(huaseLen - 5, huaseLen));
				break;
			}
			index++;
		}
		if (huaseIndex == 0) {
			return null;
		}
		
		
	//		winCard.setType(5);
	//		winCard.huase=huaseIndex;
	//		winCard.
	//		return winCard;
		return new WinCardEntity(5, huaseIndex, copySameColor, copySameColor);// {type:
																				// 5,
																				// arr1:
																				// copySameColor,
																				// huase:
																				// huaseIndex};
	}

	public static int countCardHuaSe(String huase) {
		int frame = 0;
		if ("d".equals(huase)) {// 方块
			frame = 1;
		} else if ("c".equals(huase)) {// 梅花
			frame = 2;
		} else if ("h".equals(huase)) {// 红桃
			frame = 3;
		} else if ("s".equals(huase)) {// 黑桃
			frame = 4;
		}
		return frame;
	}

	public static int countCardNum(String cardvalue) {
		int frame = 0;
		if (cardvalue.equals("A")) {
			frame = 1;
		} else if (cardvalue.equals("T")) {
			frame = 10;
		} else if (cardvalue.equals("J")) {
			frame = 11;
		} else if (cardvalue.equals("Q")) {
			frame = 12;
		} else if (cardvalue.equals("K")) {
			frame = 13;
		} else {
			frame = Integer.valueOf(cardvalue);
		}
		return frame;
	}*/

	public static void CMD_FACE(BaseCommandObject cmdObject) {
		UserInfoEntity user = cmdObject.getUser();
		if (user != null) {
			if (user.seatId < 1)
				return;
			int pcate = cmdObject.readInt();
			int pframe = cmdObject.readInt();
			cmdObject.writeBegin();
			cmdObject.writeInt(user.userId);
			cmdObject.writeInt(pcate);
			cmdObject.writeInt(pframe);
			cmdObject.writeEnd();
//			UserMgr.I().broadCastToRoomUsers(cmdObject);
		}
	}

	public static void CMD_TODAYCORNUCOPIALIST(BaseCommandObject cmdObject) {

	}

	public static void CMD_MYCORNUCOPIALIST(BaseCommandObject cmdObject) {

	}
}
